package com.frank.redis.shard;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.frank.zk.io.Factory;
import com.frank.zk.io.Writable;

import redis.clients.jedis.JedisShardInfo;

/**
 * 封装JedisShardInfo，从zookeeper读取数据
 *
 * @author liushaomingdev@163.com
 */
public class ShardInfo extends JedisShardInfo implements Writable {

	private static Logger LOG = LoggerFactory.getLogger(ShardInfo.class);

	protected String name;

	public ShardInfo(String host, int port) {
		super(host, port);
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public String getName() {
		return name;
	}

	@Override
	public void write(DataOutput out) throws IOException {
		String str = getHost() + ":" + getPort();
		out.write(str.getBytes());
	}

	@Override
	public void readFields(DataInput in) throws IOException {
	}

	public static class ShardInfoFactory extends Factory<ShardInfo> {
		@Override
		public ShardInfo newInstance() {
			throw new RuntimeException("not support");
		}

		@Override
		public ShardInfo readBytes(byte[] bytes) {
			if (bytes == null)
				return null;

			String value = null;
			try {
				value = new String(bytes);
				String[] values = value.split(":");
				String host = values[0];
				int port = Integer.parseInt(values[1]);
				return new ShardInfo(host, port);
			} catch (Exception e) {
				LOG.error("zookeeper data error: {}", value);
			}
			return null;
		}
	}
}
